// pages/goods_detail/goods_detail.js
import {goodsDetail} from '../../request/index';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsDetail:{},
  },
  params:{
    goods_id:0
  },
  goodsInfo:{},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let {goods_id}=options;
    this.params.goods_id=goods_id;
    this.getGoodsDetail()
  },
  getGoodsDetail(){
    goodsDetail(this.params).then(res=>{
      var obj = res.data.message;
      this.goodsInfo = res.data.message;
      this.setData({
        goodsDetail:{
          goods_name:obj.goods_name,
          goods_price:obj.goods_price,
          pics:obj.pics,
          //ipone不支持.webp这种图片格式
          // 最好找后台更换，临时写法
          goods_introduce:obj.goods_introduce.replace(/\.webp/g,".jpg"),
        }
      })
    })
  },
  // 轮播图图片预览
  handPreviewImage(e){
    var index = e.currentTarget.dataset.index
    var urls = this.data.goodsDetail.pics.map(val=>val.pics_big)
    var current =urls[index] ;
    console.log(current)
    wx.previewImage({
      current,
      urls
    });
  },
  // 加入购物车
  addCart(){
    var cart = wx.getStorageSync("cart") || [];
    var index=cart.findIndex((item)=>item.goods_id===this.goodsInfo.goods_id);
    if(index===-1){
      this.goodsInfo.num=1;
      this.goodsInfo.checked=true;
      cart.push(this.goodsInfo);
    }else{
      cart[index].num ++;
    }
    wx.setStorageSync("cart",cart);
    wx.showToast({
      title: '加入购物车成功',
      mask: true,
    });
    
  }
})